package com.song.book.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.song.book.entity.User;
import com.song.book.service.IUserService;
import com.song.book.utils.JwtUtils;
import com.song.book.utils.RedisTemplate;
import com.song.book.vo.LoginVo;
import com.song.book.vo.R;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tonysong
 * @since 2024-04-29
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private RedisTemplate template;
     @PostMapping("/login")
     public R login(@RequestBody LoginVo loginVo){
         log.info("loginVo:{}",loginVo);
         // 验证验证码是否正确
         //获取输入的验证码
         String code = loginVo.getCode();
         log.info("code:{}",code);
         //从redis中获取系统的验证吗
         String redisCode = template.getObject("captcha",String.class);
         log.info("redisCode:{}",redisCode);
         //判断验证码是否正确
         if(!StrUtil.contains(code,redisCode)) {
             return R.error(300, "验证码错误");
         }
         // 验证账号和密码
        User user = this.userService.getOne(new LambdaQueryWrapper<User>()
                 .eq(User::getUsername, loginVo.getUsername())
                 .eq(User::getPassword, loginVo.getPassword()));
         // 登录成功
         if(Objects.isNull(user)){
             return R.error(300, "账号或密码错误");
         }
         // 生成token，并保存到对象中，发送给前端
         String token=JwtUtils.createToken();
         Map<String,Object> map =new HashMap<>();
         map.put("token",token);
         map.put("user",user);
         return R.success(map);

     }
}
